<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>AI回复合理评估 - n8n工作流监控系统</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Microsoft YaHei', '微软雅黑', 'PingFang SC', 'Hiragino Sans GB', 'Heiti SC', 'WenQuanYi Micro Hei', 'Noto Sans CJK SC', 'Source Han Sans CN', Arial, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }
        
        .container {
            max-width: 1400px;
            margin: 0 auto;
        }
        
        .header {
            text-align: center;
            color: white;
            margin-bottom: 30px;
        }
        
        .header h1 {
            font-size: 2.5em;
            margin-bottom: 10px;
        }
        
        .back-btn {
            background: white;
            color: #667eea;
            border: none;
            padding: 12px 30px;
            border-radius: 25px;
            font-size: 1em;
            font-weight: bold;
            cursor: pointer;
            margin-top: 15px;
            transition: all 0.3s;
            box-shadow: 0 4px 15px rgba(0,0,0,0.2);
            text-decoration: none;
            display: inline-block;
        }
        
        .back-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(0,0,0,0.3);
        }
        
        .main-section {
            background: white;
            border-radius: 15px;
            padding: 40px;
            box-shadow: 0 4px 15px rgba(0,0,0,0.1);
            text-align: center;
        }
        
        .evaluate-btn {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            padding: 20px 50px;
            border-radius: 50px;
            font-size: 1.3em;
            font-weight: bold;
            cursor: pointer;
            transition: all 0.3s;
            box-shadow: 0 4px 15px rgba(0,0,0,0.2);
            margin: 30px auto;
            display: inline-block;
        }
        
        .evaluate-btn:hover {
            transform: translateY(-3px);
            box-shadow: 0 6px 25px rgba(0,0,0,0.3);
        }
        
        .evaluate-btn:disabled {
            background: #ccc;
            cursor: not-allowed;
            transform: none;
        }
        
        .progress-section {
            display: none;
            margin: 30px 0;
        }
        
        .progress-bar {
            width: 100%;
            height: 30px;
            background: #e5e7eb;
            border-radius: 15px;
            overflow: hidden;
            margin-bottom: 10px;
        }
        
        .progress-fill {
            height: 100%;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            width: 0%;
            transition: width 0.3s;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-weight: bold;
        }
        
        .progress-text {
            text-align: center;
            color: #667eea;
            font-weight: bold;
            margin-top: 10px;
        }
        
        .stats-section {
            background: white;
            border-radius: 15px;
            padding: 40px;
            box-shadow: 0 4px 15px rgba(0,0,0,0.1);
            margin-top: 30px;
            display: none;
        }
        
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
            margin: 30px 0;
        }
        
        .stat-card {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 30px;
            border-radius: 15px;
            text-align: center;
            box-shadow: 0 4px 15px rgba(0,0,0,0.2);
        }
        
        .stat-card.success {
            background: linear-gradient(135deg, #10b981 0%, #059669 100%);
        }
        
        .stat-card.warning {
            background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%);
        }
        
        .stat-card .label {
            font-size: 1em;
            margin-bottom: 10px;
            opacity: 0.9;
        }
        
        .stat-card .value {
            font-size: 3em;
            font-weight: bold;
            margin-bottom: 5px;
        }
        
        .stat-card .subtext {
            font-size: 0.9em;
            opacity: 0.8;
        }
        
        .action-buttons {
            display: none;
            justify-content: center;
            gap: 20px;
            margin-top: 30px;
        }
        
        .action-btn {
            padding: 15px 40px;
            border-radius: 25px;
            font-size: 1.1em;
            font-weight: bold;
            cursor: pointer;
            border: none;
            transition: all 0.3s;
            box-shadow: 0 4px 15px rgba(0,0,0,0.2);
        }
        
        .action-btn.primary {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }
        
        .action-btn.success {
            background: linear-gradient(135deg, #10b981 0%, #059669 100%);
            color: white;
        }
        
        .action-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(0,0,0,0.3);
        }
        
        .message-list-section {
            background: white;
            border-radius: 15px;
            padding: 40px;
            box-shadow: 0 4px 15px rgba(0,0,0,0.1);
            margin-top: 30px;
            display: none;
        }
        
        .message-list {
            max-height: 600px;
            overflow-y: auto;
            margin-top: 20px;
        }
        
        .message-item {
            background: #f8f9fa;
            border-left: 4px solid #667eea;
            padding: 20px;
            margin-bottom: 20px;
            border-radius: 5px;
            text-align: left;
        }
        
        .message-item.reasonable {
            border-left-color: #10b981;
            background: #f0fdf4;
        }
        
        .message-item.unreasonable {
            border-left-color: #f59e0b;
            background: #fffbeb;
        }
        
        .message-header {
            display: flex;
            justify-content: space-between;
            margin-bottom: 15px;
            padding-bottom: 10px;
            border-bottom: 2px solid #e5e7eb;
        }
        
        .candidate-name {
            font-weight: bold;
            color: #667eea;
            font-size: 1.1em;
        }
        
        .score-badge {
            padding: 5px 15px;
            border-radius: 20px;
            font-weight: bold;
            color: white;
        }
        
        .score-badge.reasonable {
            background: #10b981;
        }
        
        .score-badge.unreasonable {
            background: #f59e0b;
        }
        
        .message-content {
            margin-bottom: 15px;
        }
        
        .message-box {
            background: #f9fafb;
            padding: 15px;
            border-radius: 8px;
            margin-bottom: 10px;
            border-left: 3px solid #667eea;
        }
        
        .message-box.user {
            border-left-color: #10b981;
        }
        
        .message-box.ai {
            border-left-color: #667eea;
        }
        
        .message-label {
            font-weight: bold;
            color: #667eea;
            margin-bottom: 5px;
        }
        
        .message-text {
            color: #666;
            line-height: 1.6;
        }
        
        /* 🔥 新增：多条用户消息的样式 */
        .multiple-user-messages {
            display: flex;
            flex-direction: column;
            gap: 12px;
        }
        
        .user-message-count-badge {
            background: linear-gradient(135deg, #10b981 0%, #059669 100%);
            color: white;
            padding: 8px 16px;
            border-radius: 20px;
            font-size: 0.9em;
            font-weight: bold;
            text-align: center;
            box-shadow: 0 2px 8px rgba(16, 185, 129, 0.3);
            margin-bottom: 5px;
        }
        
        .multiple-user-message-item {
            background: #f0fdf4;
            padding: 12px;
            border-radius: 8px;
            border-left: 3px solid #10b981;
        }
        
        .user-message-index {
            font-weight: bold;
            color: #059669;
            font-size: 0.95em;
            margin-bottom: 6px;
        }
        
        .user-message-content {
            color: #374151;
            line-height: 1.6;
            padding-left: 10px;
        }
        
        .single-user-message {
            color: #374151;
            line-height: 1.6;
        }
        
        .message-timestamp {
            font-size: 0.8em;
            color: #999;
            margin-top: 8px;
            font-style: italic;
            text-align: right;
        }
        
        .message-timestamp::before {
            content: "🕒 ";
        }
        
        .evaluation-reason {
            background: #fff;
            padding: 15px;
            border-radius: 8px;
            margin-top: 10px;
        }
        
        .reason-text {
            color: #666;
            line-height: 1.6;
        }
        
        /* 日期选择器样式 */
        .date-selector-section {
            background: #f8f9fa;
            padding: 25px;
            border-radius: 15px;
            margin: 20px 0;
            border: 2px solid #e5e7eb;
        }
        
        .date-selector-group {
            margin: 15px 0;
            display: flex;
            align-items: center;
            gap: 15px;
            flex-wrap: wrap;
        }
        
        .date-selector-group label {
            font-size: 1em;
            font-weight: 500;
            color: #333;
            min-width: 120px;
        }
        
        .date-selector-group select {
            flex: 1;
            padding: 10px 15px;
            border-radius: 8px;
            border: 2px solid #667eea;
            font-size: 1em;
            color: #667eea;
            cursor: pointer;
            min-width: 200px;
        }
        
        .date-range-group {
            margin: 15px 0;
            display: flex;
            gap: 20px;
            flex-wrap: wrap;
        }
        
        .date-input-wrapper {
            display: flex;
            align-items: center;
            gap: 10px;
            flex: 1;
            min-width: 250px;
        }
        
        .date-input-wrapper label {
            font-size: 1em;
            font-weight: 500;
            color: #333;
            min-width: 80px;
        }
        
        .date-input-wrapper input[type="date"] {
            flex: 1;
            padding: 10px 15px;
            border-radius: 8px;
            border: 2px solid #667eea;
            font-size: 1em;
            color: #667eea;
            cursor: pointer;
        }
        
        .quick-buttons {
            margin-top: 15px;
            display: flex;
            gap: 10px;
            flex-wrap: wrap;
            justify-content: center;
        }
        
        .quick-btn {
            padding: 8px 20px;
            border-radius: 20px;
            border: 2px solid #667eea;
            background: white;
            color: #667eea;
            font-size: 0.95em;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s;
        }
        
        .quick-btn:hover {
            background: #667eea;
            color: white;
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
        }
        
        .quick-btn:active {
            transform: translateY(0);
        }
        
        .message-limit {
            margin: 30px auto;
            display: flex;
            justify-content: center;
            align-items: center;
            gap: 15px;
        }
        
        .message-limit label {
            font-size: 1.1em;
            font-weight: 500;
            color: #333;
        }
        
        .message-limit select {
            padding: 12px 20px;
            border-radius: 25px;
            border: 2px solid #667eea;
            font-size: 1.1em;
            font-weight: bold;
            color: #667eea;
            cursor: pointer;
        }
        
        /* 弹窗样式 */
        .modal-overlay {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0, 0, 0, 0.5);
            z-index: 1000;
            justify-content: center;
            align-items: center;
        }
        
        .modal-overlay.active {
            display: flex;
        }
        
        .modal {
            background: white;
            border-radius: 15px;
            padding: 40px;
            max-width: 800px;
            max-height: 90vh;
            overflow-y: auto;
            box-shadow: 0 10px 40px rgba(0,0,0,0.3);
        }
        
        .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            padding-bottom: 15px;
            border-bottom: 2px solid #e5e7eb;
        }
        
        .modal-title {
            font-size: 1.8em;
            color: #667eea;
            font-weight: bold;
        }
        
        .close-btn {
            background: #ef4444;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 25px;
            font-size: 1em;
            cursor: pointer;
            transition: all 0.3s;
        }
        
        .close-btn:hover {
            background: #dc2626;
            transform: scale(1.05);
        }
        
        .modal-content {
            margin-bottom: 20px;
        }
        
        .label-display {
            margin-bottom: 20px;
            padding: 15px;
            border-radius: 10px;
            background: #f8f9fa;
        }
        
        .label-display.reasonable {
            background: #f0fdf4;
            border: 2px solid #10b981;
        }
        
        .label-display.unreasonable {
            background: #fffbeb;
            border: 2px solid #f59e0b;
        }
        
        .label-text {
            font-size: 1.2em;
            font-weight: bold;
            color: #667eea;
        }
        
        .label-text.reasonable {
            color: #10b981;
        }
        
        .label-text.unreasonable {
            color: #f59e0b;
        }
        
        .feedback-form {
            margin-top: 20px;
        }
        
        .form-group {
            margin-bottom: 20px;
        }
        
        .form-label {
            display: block;
            font-weight: bold;
            margin-bottom: 10px;
            color: #333;
        }
        
        .form-input {
            width: 100%;
            padding: 12px;
            border: 2px solid #e5e7eb;
            border-radius: 8px;
            font-size: 1em;
            resize: vertical;
        }
        
        .form-input:focus {
            outline: none;
            border-color: #667eea;
        }
        
        .form-select {
            width: 100%;
            padding: 12px;
            border: 2px solid #e5e7eb;
            border-radius: 8px;
            font-size: 1em;
        }
        
        .form-actions {
            display: flex;
            gap: 15px;
            justify-content: flex-end;
            margin-top: 30px;
        }
        
        .form-btn {
            padding: 12px 30px;
            border-radius: 25px;
            font-size: 1.1em;
            font-weight: bold;
            cursor: pointer;
            border: none;
            transition: all 0.3s;
        }
        
        .form-btn.save {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }
        
        .form-btn.cancel {
            background: #e5e7eb;
            color: #666;
        }
        
        .form-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 15px rgba(0,0,0,0.2);
        }
        
        .message-item {
            cursor: pointer;
            transition: all 0.3s;
        }
        
        .message-item:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 20px rgba(0,0,0,0.1);
        }
        
        .evaluation-history {
            background: #fff;
            padding: 15px;
            border-radius: 8px;
            margin-top: 10px;
            border: 1px solid #e5e7eb;
        }
        
        .evaluation-history-inline {
            background: #f8f9fa;
            padding: 10px;
            border-radius: 8px;
            margin-top: 10px;
            border: 1px solid #e5e7eb;
        }
        
        .history-header {
            font-weight: bold;
            color: #667eea;
            margin-bottom: 10px;
            font-size: 0.9em;
        }
        
        .history-list {
            max-height: 200px;
            overflow-y: auto;
        }
        
        .history-item {
            background: #f9fafb;
            padding: 8px;
            border-radius: 5px;
            margin-bottom: 8px;
            border-left: 3px solid #667eea;
        }
        
        .history-item.reasonable {
            border-left-color: #10b981;
            background: #f0fdf4;
        }
        
        .history-item.unreasonable {
            border-left-color: #f59e0b;
            background: #fffbeb;
        }
        
        .history-item-content {
            font-size: 0.85em;
            color: #666;
            line-height: 1.5;
        }
        
        .history-item-time {
            font-size: 0.75em;
            color: #999;
            margin-top: 5px;
        }

        .history-empty {
            padding: 10px;
            color: #777;
            font-size: 0.85em;
        }

        .history-toggle {
            margin-top: 10px;
            background: #4f46e5;
            border: none;
            color: #fff;
            padding: 6px 16px;
            border-radius: 999px;
            font-size: 0.85em;
            cursor: pointer;
            transition: background 0.2s ease;
        }

        .history-toggle:hover {
            background: #4338ca;
        }
        
        .latest-evaluation {
            background: #f8f9fa;
            padding: 10px;
            border-radius: 5px;
            margin-top: 10px;
            border: 1px solid #e5e7eb;
        }
        
        .latest-evaluation.reasonable {
            border-left-color: #10b981;
            border-left-width: 3px;
            background: #f0fdf4;
        }
        
        .latest-evaluation.unreasonable {
            border-left-color: #f59e0b;
            border-left-width: 3px;
            background: #fffbeb;
        }
        
        /* 搜索框样式 */
        .search-container {
            position: sticky;
            top: 0;
            z-index: 100;
            margin: 20px 0;
            padding: 20px;
            background: #f8f9fa;
            border-radius: 10px;
            border: 2px solid #e5e7eb;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }
        
        .search-box {
            display: flex;
            align-items: center;
            gap: 15px;
            flex-wrap: wrap;
        }
        
        .search-input-wrapper {
            flex: 1;
            min-width: 300px;
            position: relative;
        }
        
        .search-input {
            width: 100%;
            padding: 12px 45px 12px 15px;
            border: 2px solid #667eea;
            border-radius: 25px;
            font-size: 1em;
            outline: none;
            transition: all 0.3s;
        }
        
        .search-input:focus {
            border-color: #764ba2;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        }
        
        .search-icon {
            position: absolute;
            right: 15px;
            top: 50%;
            transform: translateY(-50%);
            color: #667eea;
            font-size: 1.2em;
        }
        
        .search-stats {
            color: #667eea;
            font-weight: 600;
            font-size: 0.95em;
            padding: 8px 20px;
            background: white;
            border-radius: 20px;
            border: 2px solid #667eea;
        }
        
        .clear-search-btn {
            padding: 10px 25px;
            background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);
            color: white;
            border: none;
            border-radius: 20px;
            font-size: 0.95em;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s;
            box-shadow: 0 2px 5px rgba(239, 68, 68, 0.3);
        }
        
        .clear-search-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 10px rgba(239, 68, 68, 0.4);
        }
        
        .clear-search-btn:disabled {
            background: #d1d5db;
            cursor: not-allowed;
            box-shadow: none;
            transform: none;
        }
        
        /* 排序按钮样式 */
        .sort-time-btn {
            padding: 10px 25px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            border-radius: 20px;
            font-size: 0.95em;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s;
            box-shadow: 0 2px 5px rgba(102, 126, 234, 0.3);
            display: flex;
            align-items: center;
            gap: 8px;
        }
        
        .sort-time-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 10px rgba(102, 126, 234, 0.4);
        }
        
        .sort-time-btn:active {
            transform: translateY(0);
        }
        
        .sort-time-btn .sort-icon {
            font-size: 1.1em;
            transition: transform 0.3s;
        }
        
        .sort-time-btn[data-order="desc"] .sort-icon {
            transform: rotate(180deg);
        }
        
        .message-item.hidden {
            display: none !important;
        }
        
        /* 消息列表容器最小高度，避免晃动 */
        .message-list {
            min-height: 200px;
            transition: none;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>🔍 AI回复合理评估</h1>
            <a href="index.html" class="back-btn">← 返回主页</a>
        </div>
        
        <div class="main-section">
            <h2 id="mainTitle">评估AI回复是否合理</h2>
            <p id="mainDescription">系统会自动将用户消息和AI回复配对，并评估AI回复是否合理</p>
            
            <!-- 日期选择器区域 -->
            <div class="date-selector-section">
                <h3 style="color: #667eea; margin-bottom: 20px;">📅 选择评估时间范围</h3>
                
                <!-- 快捷日期选择 -->
                <div class="date-selector-group">
                    <label for="quickDateSelect">快捷日期选择：</label>
                    <select id="quickDateSelect">
                        <option value="">-- 选择一个日期 --</option>
                        <!-- 动态填充 -->
                    </select>
                </div>
                
                <!-- 自定义日期范围 -->
                <div class="date-range-group">
                    <div class="date-input-wrapper">
                        <label for="startDate">开始日期：</label>
                        <input type="date" id="startDate" />
                    </div>
                    <div class="date-input-wrapper">
                        <label for="endDate">结束日期：</label>
                        <input type="date" id="endDate" />
                    </div>
                </div>
                
                <!-- 快捷按钮 -->
                <div class="quick-buttons">
                    <button class="quick-btn" onclick="selectToday()">今天</button>
                    <button class="quick-btn" onclick="selectYesterday()">昨天</button>
                    <button class="quick-btn" onclick="selectLast3Days()">最近3天</button>
                    <button class="quick-btn" onclick="selectLast7Days()">最近7天</button>
                    <button class="quick-btn" onclick="clearDateSelection()">清除日期</button>
                </div>
            </div>
            
            <!-- 条数选择器 -->
            <div class="message-limit">
                <label for="messageLimit">该范围内评估条数：</label>
                <select id="messageLimit">
                    <option value="0" selected>不限制</option>
                    <option value="10">10对</option>
                    <option value="20">20对</option>
                    <option value="50">50对</option>
                    <option value="100">100对</option>
                </select>
            </div>
            
            <div style="text-align: center;">
                <button id="evaluateBtn" class="evaluate-btn" onclick="startEvaluation()">
                    🚀 开始评估
                </button>
            </div>
            
            <div id="progressSection" class="progress-section">
                <div class="progress-bar">
                    <div id="progressFill" class="progress-fill">0%</div>
                </div>
                <div id="progressText" class="progress-text">准备开始...</div>
            </div>
            
            <div id="actionButtons" class="action-buttons">
                <button class="action-btn primary" onclick="showMessages('reasonable')">✅ 查看合理回复</button>
                <button class="action-btn warning" onclick="showMessages('unreasonable')">⚠️ 查看不合理回复</button>
                <button class="action-btn success" onclick="exportData()">📥 导出评估结果</button>
            </div>
        </div>
        
        <div id="statsSection" class="stats-section">
            <h2>评估统计结果</h2>
            <div class="stats-grid" id="statsGrid">
                <!-- 动态填充 -->
            </div>
        </div>
        
        <div id="messageListSection" class="message-list-section">
            <h2>消息列表</h2>
            
            <!-- 搜索框区域 -->
            <div class="search-container">
                <div class="search-box">
                    <div class="search-input-wrapper">
                        <input 
                            type="text" 
                            id="messageSearchInput" 
                            class="search-input" 
                            placeholder="🔍 输入关键词搜索候选人姓名或对话内容..."
                            oninput="debouncedFilterMessages()"
                            autocomplete="off"
                        />
                        <span class="search-icon">🔍</span>
                    </div>
                    <div class="search-stats" id="searchStats">
                        显示全部消息
                    </div>
                    <button 
                        class="sort-time-btn" 
                        id="sortTimeBtn"
                        onclick="toggleSortOrder()"
                        data-order="desc"
                        title="点击切换时间排序"
                    >
                        <span class="sort-icon">⬇</span>
                        <span id="sortTimeText">时间降序</span>
                    </button>
                    <button 
                        class="clear-search-btn" 
                        id="clearSearchBtn"
                        onclick="clearSearch()"
                        disabled
                    >
                        ✕ 清除搜索
                    </button>
                </div>
            </div>
            
            <div id="messageList" class="message-list">
                <!-- 动态填充 -->
            </div>
        </div>
        
        <!-- 弹窗 -->
        <div id="feedbackModal" class="modal-overlay">
            <div class="modal">
                <div class="modal-header">
                    <div class="modal-title">📝 编辑评估标签</div>
                    <button class="close-btn" onclick="closeModal()">✕ 关闭</button>
                </div>
                <div class="modal-content">
                    <div id="currentLabel" class="label-display">
                        <span class="label-text">当前标签</span>
                    </div>
                    
                    <div class="message-box user">
                        <div class="message-label">👤 用户消息：</div>
                        <div id="modalUserMessage" class="message-text"></div>
                    </div>
                    
                    <div class="message-box ai">
                        <div class="message-label">🤖 AI回复：</div>
                        <div id="modalAiReply" class="message-text"></div>
                    </div>
                    
                    <div class="evaluation-reason">
                        <strong>评估理由：</strong>
                        <div id="modalEvaluationReason" class="reason-text"></div>
                    </div>
                    
                    <div class="prompt-section">
                        <div class="form-group">
                            <label class="form-label">📋 本次评估使用的提示词：</label>
                            <textarea id="currentPrompt" class="form-input" rows="6" readonly placeholder="提示词将在这里显示..."></textarea>
                            <div style="margin-top: 10px; display: flex; gap: 10px;">
                                <button class="form-btn" style="background: #3b82f6; color: white; padding: 8px 20px; border-radius: 20px; font-size: 0.9em;" onclick="editPrompt()">
                                    ✏️ 编辑提示词
                                </button>
                                <button class="form-btn" style="background: #10b981; color: white; padding: 8px 20px; border-radius: 20px; font-size: 0.9em;" onclick="comparePrompt()">
                                    🔍 查看原提示词
                                </button>
                            </div>
                            <div id="originalPromptSection" style="display: none; margin-top: 15px; padding: 15px; background: #f8f9fa; border-radius: 8px; border-left: 3px solid #667eea;">
                                <strong style="color: #667eea; display: block; margin-bottom: 10px;">📜 原评估提示词：</strong>
                                <textarea id="originalPrompt" class="form-input" rows="6" readonly style="font-size: 0.9em;"></textarea>
                            </div>
                        </div>
                    </div>
                    
                    <div class="feedback-form">
                        <div class="form-group">
                            <label class="form-label">修改标签：</label>
                            <select id="newLabel" class="form-select">
                                <option value="reasonable">✅ 合理</option>
                                <option value="unreasonable">⚠️ 不合理</option>
                            </select>
                        </div>
                        
                        <div class="form-group">
                            <label class="form-label">我的建议：</label>
                            <textarea id="userFeedback" class="form-input" rows="4" placeholder="请输入您的建议...例如：AI评估不准确，因为..."></textarea>
                        </div>
                        
                        <div class="form-actions">
                            <button class="form-btn cancel" onclick="closeModal()">取消</button>
                            <button class="form-btn save" onclick="saveFeedback()">💾 保存反馈</button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 提示词编辑弹窗 -->
        <div id="promptModal" class="modal-overlay">
            <div class="modal" style="max-width: 600px;">
                <div class="modal-header">
                    <div class="modal-title">✏️ 编辑评估提示词</div>
                    <button class="close-btn" onclick="closePromptModal()">✕ 关闭</button>
                </div>
                <div class="modal-content">
                    <div class="form-group">
                        <label class="form-label">提示词内容：</label>
                        <textarea id="newPrompt" class="form-input" rows="12" placeholder="请输入新的评估提示词..."></textarea>
                        <p style="font-size: 0.85em; color: #666; margin-top: 10px;">
                            提示：修改提示词将影响后续所有评估结果，请谨慎修改。
                        </p>
                    </div>
                    <div class="form-actions">
                        <button class="form-btn cancel" onclick="closePromptModal()">取消</button>
                        <button class="form-btn save" onclick="savePrompt()">💾 保存提示词</button>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <script>
        let currentEditingItem = null;
        let evaluationData = null;
        let currentPrompt = ''; // 存储当前使用的提示词
        let originalPrompt = ''; // 存储原始评估使用的提示词
        
        // 时间格式化函数
        function formatTimestamp(timestamp) {
            if (!timestamp) {
                console.log('[时间格式化] 时间戳为空');
                return '时间未知';
            }
            
            try {
                // 支持多种时间格式
                let date;
                if (timestamp instanceof Date) {
                    date = timestamp;
                } else if (typeof timestamp === 'string') {
                    // 替换空格为T以支持ISO格式
                    const isoFormat = timestamp.replace(' ', 'T');
                    date = new Date(isoFormat);
                } else {
                    date = new Date(timestamp);
                }
                
                // 检查日期是否有效
                if (isNaN(date.getTime())) {
                    console.warn('[时间格式化] 无效的时间戳:', timestamp);
                    return timestamp; // 返回原始值
                }
                
                // 格式化为本地时间
                const year = date.getFullYear();
                const month = String(date.getMonth() + 1).padStart(2, '0');
                const day = String(date.getDate()).padStart(2, '0');
                const hours = String(date.getHours()).padStart(2, '0');
                const minutes = String(date.getMinutes()).padStart(2, '0');
                const seconds = String(date.getSeconds()).padStart(2, '0');
                
                const formatted = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
                console.log(`[时间格式化] 原始: ${timestamp} -> 格式化: ${formatted}`);
                return formatted;
            } catch (e) {
                console.error('[时间格式化] 格式化失败:', e, '原始值:', timestamp);
                return timestamp || '时间未知';
            }
        }
        
        // ========================================
        // 日期选择相关函数
        // ========================================
        
        // 加载可用的消息日期列表
        async function loadMessageDates() {
            try {
                console.log('[日期加载] 开始加载可用日期列表...');
                const response = await fetch('/api/message-dates');
                
                if (!response.ok) {
                    console.error('[日期加载] API调用失败:', response.status);
                    return;
                }
                
                const data = await response.json();
                console.log('[日期加载] 成功获取日期数据:', data);
                
                if (data.success && data.dates && data.dates.length > 0) {
                    console.log(`[日期加载] 共有 ${data.dates.length} 个日期`);
                    
                    // 填充快捷日期下拉框
                    const quickDateSelect = document.getElementById('quickDateSelect');
                    quickDateSelect.innerHTML = '<option value="">-- 选择一个日期 --</option>';
                    
                    data.dates.forEach(dateInfo => {
                        const option = document.createElement('option');
                        option.value = dateInfo.date;
                        option.textContent = `${dateInfo.date} (${dateInfo.pair_count}对消息)`;
                        quickDateSelect.appendChild(option);
                    });
                    
                    console.log('[日期加载] ✅ 日期列表加载完成');
                    
                    // 添加快捷日期选择的change事件
                    quickDateSelect.addEventListener('change', function() {
                        const selectedDate = this.value;
                        if (selectedDate) {
                            console.log('[快捷日期] 选择了日期:', selectedDate);
                            document.getElementById('startDate').value = selectedDate;
                            document.getElementById('endDate').value = selectedDate;
                        }
                    });
                } else {
                    console.warn('[日期加载] 没有可用的日期数据');
                }
            } catch (error) {
                console.error('[日期加载] 加载日期列表失败:', error);
            }
        }
        
        // 选择今天
        function selectToday() {
            const today = new Date().toISOString().split('T')[0];
            console.log('[快捷按钮] 选择今天:', today);
            document.getElementById('startDate').value = today;
            document.getElementById('endDate').value = today;
            document.getElementById('quickDateSelect').value = '';
        }
        
        // 选择昨天
        function selectYesterday() {
            const yesterday = new Date();
            yesterday.setDate(yesterday.getDate() - 1);
            const dateStr = yesterday.toISOString().split('T')[0];
            console.log('[快捷按钮] 选择昨天:', dateStr);
            document.getElementById('startDate').value = dateStr;
            document.getElementById('endDate').value = dateStr;
            document.getElementById('quickDateSelect').value = '';
        }
        
        // 选择最近3天
        function selectLast3Days() {
            const endDate = new Date();
            const startDate = new Date();
            startDate.setDate(startDate.getDate() - 2);
            
            const startStr = startDate.toISOString().split('T')[0];
            const endStr = endDate.toISOString().split('T')[0];
            
            console.log('[快捷按钮] 选择最近3天:', startStr, '-', endStr);
            document.getElementById('startDate').value = startStr;
            document.getElementById('endDate').value = endStr;
            document.getElementById('quickDateSelect').value = '';
        }
        
        // 选择最近7天
        function selectLast7Days() {
            const endDate = new Date();
            const startDate = new Date();
            startDate.setDate(startDate.getDate() - 6);
            
            const startStr = startDate.toISOString().split('T')[0];
            const endStr = endDate.toISOString().split('T')[0];
            
            console.log('[快捷按钮] 选择最近7天:', startStr, '-', endStr);
            document.getElementById('startDate').value = startStr;
            document.getElementById('endDate').value = endStr;
            document.getElementById('quickDateSelect').value = '';
        }
        
        // 清除日期选择
        function clearDateSelection() {
            console.log('[快捷按钮] 清除日期选择');
            document.getElementById('startDate').value = '';
            document.getElementById('endDate').value = '';
            document.getElementById('quickDateSelect').value = '';
        }
        
        // 页面加载时检测是否有评估数据并加载可用日期
        window.addEventListener('DOMContentLoaded', async function() {
            console.log('========== [回复合理评估] 页面加载开始 ==========');
            console.log('[回复合理评估] 检测是否有已保存的评估数据...');
            
            // 加载可用的日期列表
            await loadMessageDates();
            
            // 检测并加载已有评估数据
            await checkAndLoadExistingEvaluation();
        });
        
        // 检测并加载已有评估数据
        async function checkAndLoadExistingEvaluation() {
            try {
                console.log('[回复合理评估] 调用 /api/reply-reasonable-statistics API...');
                const response = await fetch('/api/reply-reasonable-statistics');
                
                if (!response.ok) {
                    console.log('[回复合理评估] API调用失败:', response.status);
                    return;
                }
                
                const data = await response.json();
                console.log('[回复合理评估] API返回数据:', data);
                
                if (data.has_data) {
                    console.log('[回复合理评估] 找到已保存的评估数据');
                    console.log('[回复合理评估] 评估时间:', data.timestamp);
                    console.log('[回复合理评估] 合理回复数:', data.reasonable_count);
                    console.log('[回复合理评估] 不合理回复数:', data.unreasonable_count);
                    
                    // 加载评估数据
                    await loadEvaluationData(data);
                } else {
                    console.log('[回复合理评估] 暂无已保存的评估数据');
                }
            } catch (error) {
                console.error('[回复合理评估] 检测评估数据时发生错误:', error);
            }
        }
        
        // 加载评估数据
        async function loadEvaluationData(statistics) {
            try {
                console.log('========== [回复合理评估] 开始加载评估数据 ==========');
                console.log('[回复合理评估] 接收到的统计数据:', statistics);
                
                // 修改：保留开始评估按钮和选择器，只更新标题和描述
                const mainTitle = document.getElementById('mainTitle');
                const mainDescription = document.getElementById('mainDescription');
                const evaluateBtn = document.getElementById('evaluateBtn');
                const messageLimitSelect = document.getElementById('messageLimit');
                
                console.log('[回复合理评估] mainTitle元素:', mainTitle);
                console.log('[回复合理评估] mainTitle当前文本内容:', mainTitle ? mainTitle.textContent : 'null');
                console.log('[回复合理评估] 准备更新主标题为: 历史评估结果');
                
                if (mainTitle) {
                    const oldText = mainTitle.textContent;
                    mainTitle.textContent = '历史评估结果';
                    const newText = mainTitle.textContent;
                    console.log('[回复合理评估] 主标题更新: [' + oldText + '] -> [' + newText + ']');
                    console.log('[回复合理评估] 主标题更新成功');
                } else {
                    console.error('[回复合理评估] 错误：mainTitle元素不存在');
                }
                
                if (mainDescription) {
                    mainDescription.textContent = '查看历史评估结果或继续进行新的评估';
                    console.log('[回复合理评估] 已更新描述文字');
                }
                
                // 确保评估按钮始终可见且可用
                if (evaluateBtn) {
                    evaluateBtn.style.display = 'block';
                    evaluateBtn.disabled = false;
                    evaluateBtn.textContent = '🚀 开始评估';
                    console.log('[回复合理评估] 已确保评估按钮可见且可用');
                }
                
                // 确保消息条数选择器可见
                if (messageLimitSelect && messageLimitSelect.parentElement) {
                    messageLimitSelect.parentElement.style.display = 'flex';
                    console.log('[回复合理评估] 已确保消息条数选择器可见');
                }
                
                // 显示统计结果
                displayStats(statistics);
                console.log('[回复合理评估] 已显示统计结果');
                
                // 显示操作按钮
                document.getElementById('actionButtons').style.display = 'flex';
                console.log('[回复合理评估] 已显示操作按钮');
                
                // 构建evaluationData对象
                if (statistics.data && typeof statistics.data === 'object') {
                    evaluationData = statistics.data;
                    console.log('[回复合理评估] 使用完整的评估数据:', evaluationData);
                } else {
                    evaluationData = {
                        success: true,
                        total_pairs: statistics.total_pairs || 0,
                        evaluated_count: statistics.evaluated_count || 0,
                        reasonable_count: statistics.reasonable_count || 0,
                        unreasonable_count: statistics.unreasonable_count || 0,
                        failed_count: statistics.failed_count || 0,
                        timestamp: statistics.timestamp,
                        all_evaluations: []
                    };
                    console.log('[回复合理评估] 构建基础统计数据:', evaluationData);
                }
                
                console.log('========== [回复合理评估] 评估数据加载完成 ==========');
                
            } catch (error) {
                console.error('[回复合理评估] 加载评估数据时发生错误:', error);
            }
        }
        
        // 开始评估
        async function startEvaluation() {
            console.log('[回复合理评估] 开始评估流程');
            const btn = document.getElementById('evaluateBtn');
            btn.disabled = true;
            btn.textContent = '评估中...';
            
            // 显示进度条
            document.getElementById('progressSection').style.display = 'block';
            
            try {
                // 获取选择的消息对数
                const pairLimit = parseInt(document.getElementById('messageLimit').value);
                console.log(`[回复合理评估] 获取消息对数限制: ${pairLimit}`);
                
                // 获取日期参数
                const startDate = document.getElementById('startDate').value;
                const endDate = document.getElementById('endDate').value;
                
                console.log(`[回复合理评估] 开始日期: ${startDate || '不限制'}`);
                console.log(`[回复合理评估] 结束日期: ${endDate || '不限制'}`);
                
                // 表单验证：如果没有选择任何日期，给出提示
                if (!startDate && !endDate) {
                    alert('⚠️ 请选择评估的时间范围！\n\n您可以：\n1. 使用快捷日期选择\n2. 自定义日期范围\n3. 点击快捷按钮（今天、昨天、最近N天）');
                    btn.disabled = false;
                    btn.textContent = '🚀 开始评估';
                    document.getElementById('progressSection').style.display = 'none';
                    return;
                }
                
                // 日期范围有效性验证
                if (startDate && endDate && startDate > endDate) {
                    alert('⚠️ 开始日期不能晚于结束日期！');
                    btn.disabled = false;
                    btn.textContent = '🚀 开始评估';
                    document.getElementById('progressSection').style.display = 'none';
                    return;
                }
                
                // 调用后端API进行实时评估
                updateProgress(10, '正在连接服务器...');
                
                const apiUrl = `/api/evaluate-reply-reasonable`;
                const requestBody = {
                    limit: pairLimit,
                    start_date: startDate || null,
                    end_date: endDate || null
                };
                
                console.log('[回复合理评估] 请求数据:', requestBody);
                
                const response = await fetch(apiUrl, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(requestBody)
                });
                
                console.log(`[回复合理评估] 收到响应，状态码: ${response.status}`);
                if (!response.ok) {
                    console.error(`[回复合理评估] 服务器返回错误: ${response.status} ${response.statusText}`);
                    throw new Error(`服务器返回错误: ${response.status} ${response.statusText}`);
                }
                
                updateProgress(30, '开始评估回复合理性...');
                
                const data = await response.json();
                
                if (!data.success) {
                    const errorMsg = data.error || '评估失败';
                    console.error(`[回复合理评估] 评估失败: ${errorMsg}`);
                    
                    // 如果是没有消息对的情况，显示更友好的提示
                    if (data.message_pairs_count === 0 || errorMsg.includes('没有可评估的消息对')) {
                        updateProgress(0, '查询完成，但没有找到消息对');
                        document.getElementById('progressSection').style.display = 'none';
                        alert(`📅 ${errorMsg}`);
                        btn.disabled = false;
                        btn.textContent = '🚀 开始评估';
                        return;
                    }
                    
                    throw new Error(errorMsg);
                }
                
                // 模拟进度更新
                updateProgress(50, '评估进行中...');
                await new Promise(resolve => setTimeout(resolve, 300));
                
                updateProgress(70, '正在整理结果...');
                await new Promise(resolve => setTimeout(resolve, 300));
                
                updateProgress(90, '即将完成...');
                await new Promise(resolve => setTimeout(resolve, 300));
                
                // 保存完整的评估数据
                evaluationData = data;
                
                updateProgress(100, '评估完成！');
                
                // 显示统计结果
                displayStats(data);
                console.log('[回复合理评估] 统计结果显示完成');
                
                // 显示操作按钮
                document.getElementById('actionButtons').style.display = 'flex';
                console.log('[回复合理评估] 操作按钮显示完成');
                
                // 保持按钮可点击状态
                btn.disabled = false;
                btn.textContent = '🚀 重新开始评估';
                console.log('[回复合理评估] 评估按钮已重置，可以继续评估');
                
            } catch (error) {
                console.error('[回复合理评估] 评估过程中发生错误', error);
                alert(`评估失败: ${error.message}`);
                btn.disabled = false;
                btn.textContent = '🚀 开始评估';
                document.getElementById('progressSection').style.display = 'none';
            }
        }
        
        // 更新进度条
        function updateProgress(percentage, text) {
            const progressFill = document.getElementById('progressFill');
            const progressText = document.getElementById('progressText');
            
            progressFill.style.width = percentage + '%';
            progressFill.textContent = percentage + '%';
            progressText.textContent = text;
        }
        
        // 显示统计结果
        function displayStats(data) {
            console.log('[回复合理评估] 显示统计结果:', data);
            
            const statsSection = document.getElementById('statsSection');
            statsSection.style.display = 'block';
            
            const statsGrid = document.getElementById('statsGrid');
            
            const totalPairs = data.total_pairs || 0;
            const reasonableCount = data.reasonable_count || 0;
            const unreasonableCount = data.unreasonable_count || 0;
            const failedCount = data.failed_count || 0;
            
            const reasonableRate = totalPairs > 0 ? ((reasonableCount / totalPairs) * 100).toFixed(2) : '0.00';
            
            statsGrid.innerHTML = `
                <div class="stat-card">
                    <div class="label">📊 总消息对</div>
                    <div class="value">${totalPairs}</div>
                    <div class="subtext">已评估</div>
                </div>
                <div class="stat-card success">
                    <div class="label">✅ 合理回复</div>
                    <div class="value">${reasonableCount}</div>
                    <div class="subtext">占比 ${reasonableRate}%</div>
                </div>
                <div class="stat-card warning">
                    <div class="label">⚠️ 不合理回复</div>
                    <div class="value">${unreasonableCount}</div>
                    <div class="subtext">需要关注</div>
                </div>
                <div class="stat-card">
                    <div class="label">❌ 评估失败</div>
                    <div class="value">${failedCount}</div>
                    <div class="subtext">失败次数</div>
                </div>
            `;
        }
        
        function normalizeReasonableValue(value) {
            if (typeof value === 'boolean') {
                return value;
            }
            if (typeof value === 'number') {
                return value === 1;
            }
            if (typeof value === 'string') {
                const normalized = value.trim().toLowerCase();
                if (['true', '1', 'yes', '合理', 'reasonable', '是'].includes(normalized)) {
                    return true;
                }
                if (['false', '0', 'no', '不合理', 'unreasonable', '否'].includes(normalized)) {
                    return false;
                }
            }
            return false;
        }
        
        // 🔥 新增：格式化用户消息显示（支持多条消息）
        function formatUserMessage(userMessage) {
            if (!userMessage) return '';
            
            // 检查是否包含多条消息（用\n---\n分隔）
            const messages = userMessage.split('\n---\n');
            
            if (messages.length === 1) {
                // 只有一条消息，直接显示
                return `<div class="single-user-message">${userMessage}</div>`;
            } else {
                // 多条消息，分别显示
                const messagesHtml = messages.map((msg, idx) => `
                    <div class="multiple-user-message-item">
                        <div class="user-message-index">📝 用户消息 ${idx + 1}：</div>
                        <div class="user-message-content">${msg}</div>
                    </div>
                `).join('');
                
                return `
                    <div class="multiple-user-messages">
                        <div class="user-message-count-badge">用户连续发送了 ${messages.length} 条消息</div>
                        ${messagesHtml}
                    </div>
                `;
            }
        }

        // 显示消息列表
        function showMessages(type) {
            console.log('========== [消息列表] 开始显示消息列表 ==========');
            console.log(`[消息列表] 类型: ${type}`);
            
            if (!evaluationData || !evaluationData.all_evaluations) {
                console.error('[消息列表] ❌ 没有评估数据');
                alert('暂无评估数据');
                return;
            }
            
            console.log(`[消息列表] 总评估数据数量: ${evaluationData.all_evaluations.length}`);
            
            // 🔥 关键调试：打印前5条数据的is_reasonable值
            console.log('[消息列表] 前5条数据的is_reasonable值:');
            evaluationData.all_evaluations.slice(0, 5).forEach((e, idx) => {
                const isReasonable = e.evaluation ? e.evaluation.is_reasonable : 'undefined';
                const status = e.status || 'unknown';
                console.log(`  [${idx}] is_reasonable=${isReasonable}, status=${status}, pair_id=${e.pair_id}`);
            });
            
            const messageListSection = document.getElementById('messageListSection');
            const messageList = document.getElementById('messageList');
            
            // 保存当前消息类型
            currentMessageType = type;
            
            // 过滤消息并保存原始数据
            let filteredMessages = [];
            
            if (type === 'reasonable') {
                console.log('[消息列表] 🔍 过滤合理消息 (is_reasonable === true)');
                filteredMessages = evaluationData.all_evaluations.filter(e => {
                    const hasEval = e.evaluation && e.evaluation !== null;
                    const isEvaluated = e.status === 'evaluated';
                    const isReasonable = hasEval ? normalizeReasonableValue(e.evaluation.is_reasonable) : false;

                    if (hasEval && isEvaluated) {
                        console.log(`  pair_id=${e.pair_id}: is_reasonable=${e.evaluation.is_reasonable} (${typeof e.evaluation.is_reasonable}), 匹配=${isReasonable}`);
                    }

                    
                    return hasEval && isReasonable && isEvaluated;
                });
                messageListSection.querySelector('h2').textContent = '✅ 合理回复列表';
            } else if (type === 'unreasonable') {
                console.log('[消息列表] 🔍 过滤不合理消息 (is_reasonable === false)');
                filteredMessages = evaluationData.all_evaluations.filter(e => {
                    const hasEval = e.evaluation && e.evaluation !== null;
                    const isEvaluated = e.status === 'evaluated';
                    const isUnreasonable = hasEval ? normalizeReasonableValue(e.evaluation.is_reasonable) === false : false;

                    if (hasEval && isEvaluated) {
                        console.log(`  pair_id=${e.pair_id}: is_reasonable=${e.evaluation.is_reasonable} (${typeof e.evaluation.is_reasonable}), 匹配=${isUnreasonable}`);
                    }

                    
                    return hasEval && isUnreasonable && isEvaluated;
                });
                messageListSection.querySelector('h2').textContent = '⚠️ 不合理回复列表';
            }
            
            console.log(`[消息列表] ✅ 过滤后的消息数: ${filteredMessages.length}`);
            
            // 保存原始数据用于排序
            originalMessageData = filteredMessages;
            
            // 按当前排序顺序排序消息
            filteredMessages = sortMessagesByTime(filteredMessages, currentSortOrder);
            console.log(`[消息列表] 排序方式: ${currentSortOrder === 'asc' ? '升序(早→晚)' : '降序(晚→早)'}`);
            
            // 显示消息列表
            messageList.innerHTML = filteredMessages.map((msg, index) => {
                const evaluation = msg.evaluation || {};
                const score = evaluation.score || 0;
                // 🔥 关键修复：正确获取is_reasonable值，不能使用||运算符
                const isReasonable = normalizeReasonableValue(evaluation.is_reasonable);
                const reason = evaluation.reason || '未提供理由';
                const strengths = evaluation.strengths || [];
                const weaknesses = evaluation.weaknesses || [];
                const pairId = msg.pair_id;
                const timestamp = msg.created_at || '';
                
                // 🔥 调试日志：打印每条消息的is_reasonable值
                console.log(`[消息列表] 渲染消息 pair_id=${pairId}: is_reasonable=${evaluation.is_reasonable} -> 显示为${isReasonable ? '合理' : '不合理'}, 时间戳: ${timestamp}`);

                return `
                    <div class="message-item ${isReasonable ? 'reasonable' : 'unreasonable'}" data-pair-id="${pairId}" onclick="openModal(${index}, '${type}')">
                        <div class="message-header">
                            <div class="candidate-name">${msg.candidate_name || `候选人 #${msg.candidate_id || '未知'}`}</div>
                            <div style="display: flex; gap: 10px; align-items: center;">
                                <button class="view-chat-btn" 
                                        data-candidate-id="${msg.candidate_id}" 
                                        data-candidate-name="${(msg.candidate_name || '未知').replace(/"/g, '&quot;')}"
                                        data-pair-id="${pairId}"
                                        style="padding: 5px 12px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); 
                                               color: white; border: none; border-radius: 15px; cursor: pointer; font-size: 0.85em; 
                                               transition: all 0.3s; box-shadow: 0 2px 5px rgba(0,0,0,0.2);"
                                        onmouseover="this.style.transform='translateY(-2px)'; this.style.boxShadow='0 4px 10px rgba(0,0,0,0.3)';"
                                        onmouseout="this.style.transform='translateY(0)'; this.style.boxShadow='0 2px 5px rgba(0,0,0,0.2)';">
                                    💬 查看聊天
                                </button>
                                <span class="score-badge ${msg.evaluation && normalizeReasonableValue(msg.evaluation.is_reasonable) ? 'reasonable' : 'unreasonable'}">
                                    ${msg.evaluation && normalizeReasonableValue(msg.evaluation.is_reasonable) ? '✅ 合理' : '⚠️ 不合理'}
                                    (评分: ${msg.evaluation?.score || 0}分)
                                </span>
                            </div>
                        </div>
                        <div class="message-content">
                            <div class="message-box user">
                                <div class="message-label">👤 用户消息：</div>
                                <div class="message-text">${formatUserMessage(msg.user_message)}</div>
                            </div>
                            <div class="message-box ai">
                                <div class="message-label">🤖 AI回复：</div>
                                <div class="message-text">${msg.ai_reply || ''}</div>
                            </div>
                            <div class="message-timestamp">${formatTimestamp(timestamp)}</div>
                        </div>
                        <div class="evaluation-latest" id="latest-evaluation-${pairId}">
                            <div class="latest-header">🆕 最新评估结果</div>
                            <div class="latest-body">
                                <div class="reason-text">${reason}</div>
                                ${strengths.length > 0 ? `<div><strong>优点：</strong>${strengths.join(', ')}</div>` : ''}
                                ${weaknesses.length > 0 ? `<div><strong>缺点：</strong>${weaknesses.join(', ')}</div>` : ''}
                            </div>
                        </div>
                        <div class="evaluation-history-inline" data-pair-id="${pairId}" id="history-container-${pairId}">
                            <!-- 历史记录加载区域 -->
                        </div>
                    </div>
                `;
            }).join('');
            
            messageListSection.style.display = 'block';
            
            // 保存所有消息元素供搜索使用
            allDisplayedMessages = document.querySelectorAll('.message-item');
            totalMessageCount = filteredMessages.length;
            
            // 重置搜索框
            document.getElementById('messageSearchInput').value = '';
            updateSearchStats(totalMessageCount, totalMessageCount);
            document.getElementById('clearSearchBtn').disabled = true;
            
            console.log(`[消息列表] 已保存 ${allDisplayedMessages.length} 个消息元素供搜索使用`);
            
            // 滚动到消息列表
            messageListSection.scrollIntoView({ behavior: 'smooth' });
            
            // 为每条消息加载评估记录（延迟执行，确保DOM已渲染）
            setTimeout(() => {
                console.log('[回复合理评估] 开始为', filteredMessages.length, '条消息加载评估记录');
                filteredMessages.forEach(msg => {
                    if (msg.pair_id !== undefined && msg.pair_id !== null) {
                        loadEvaluationHistory(msg.pair_id);
                    } else {
                        console.warn('[回复合理评估] 跳过无pair_id的记录', msg);
                    }
                });
                
                // 为所有查看聊天按钮添加事件监听器
                console.log('[回复合理评估] 开始为查看聊天按钮添加事件监听器');
                document.querySelectorAll('.view-chat-btn').forEach(btn => {
                    btn.addEventListener('click', function(e) {
                        e.stopPropagation(); // 阻止事件冒泡到message-item
                        e.preventDefault();
                        const candidateId = this.getAttribute('data-candidate-id');
                        const candidateName = this.getAttribute('data-candidate-name');
                        console.log('[回复合理评估] 点击查看聊天按钮:', { candidateId, candidateName });
                        viewChatHistory(candidateId, candidateName);
                    });
                });
                console.log('[回复合理评估] 查看聊天按钮事件监听器添加完成');
            }, 100);
        }
        
        // 保存当前过滤的消息列表
        let currentMessageList = [];
        let currentMessageType = '';
        let allDisplayedMessages = []; // 保存所有当前显示的消息元素
        let totalMessageCount = 0; // 总消息数
        let searchDebounceTimer = null; // 防抖定时器
        let currentSortOrder = 'desc'; // 当前排序顺序: 'asc'升序(早到晚), 'desc'降序(晚到早)
        let originalMessageData = []; // 保存原始消息数据用于排序
        
        // 打开弹窗
        function openModal(index, type) {
            console.log(`[用户反馈] 打开弹窗 - index: ${index}, type: ${type}`);
            
            // 根据type找到对应的消息列表
            let messages = [];
            if (type === 'reasonable') {
                messages = evaluationData.all_evaluations.filter(e => 
                    e.evaluation && normalizeReasonableValue(e.evaluation.is_reasonable) === true && e.status === 'evaluated'
                );
            } else if (type === 'unreasonable') {
                messages = evaluationData.all_evaluations.filter(e => 
                    e.evaluation && normalizeReasonableValue(e.evaluation.is_reasonable) === false && e.status === 'evaluated'
                );
            }
            
            if (index >= messages.length) {
                console.error(`[用户反馈] 索引超出范围: ${index} >= ${messages.length}`);
                return;
            }
            
            currentMessageList = messages;
            currentMessageType = type;
            
            const msg = messages[index];
            currentEditingItem = msg;
            
            const evaluation = msg.evaluation || {};
            // 🔥 关键修复：使用严格相等判断，不能使用||运算符
            const isReasonable = normalizeReasonableValue(evaluation.is_reasonable);
            const reason = evaluation.reason || '未提供理由';
            const score = evaluation.score || 0;
            
            console.log(`[用户反馈] 当前消息对信息:`, {
                pair_id: msg.pair_id,
                candidate_name: msg.candidate_name,
                is_reasonable_raw: evaluation.is_reasonable,
                is_reasonable_type: typeof evaluation.is_reasonable,
                isReasonable: isReasonable,
                score: score
            });
            
            // 填充弹窗内容
            const labelDisplay = document.getElementById('currentLabel');
            labelDisplay.innerHTML = `<span class="label-text ${isReasonable ? 'reasonable' : 'unreasonable'}">当前标签：${isReasonable ? '✅ 合理' : '⚠️ 不合理'} (评分: ${score}分)</span>`;
            labelDisplay.className = `label-display ${isReasonable ? 'reasonable' : 'unreasonable'}`;
            
            // 🔥 修改：使用innerHTML显示格式化的用户消息
            document.getElementById('modalUserMessage').innerHTML = formatUserMessage(msg.user_message);
            document.getElementById('modalAiReply').textContent = msg.ai_reply || '';
            document.getElementById('modalEvaluationReason').textContent = reason;
            
            // 设置默认值
            document.getElementById('newLabel').value = isReasonable ? 'reasonable' : 'unreasonable';
            document.getElementById('userFeedback').value = '';
            
            // 保存原始提示词（用于对比）
            // 从评估结果中获取原始使用的提示词，如果没有则使用当前提示词
            originalPrompt = evaluation.original_prompt || currentPrompt;
            console.log('[用户反馈] 保存原始提示词，长度:', originalPrompt.length);
            
            // 加载当前提示词
            loadCurrentPrompt();
            
            // 显示弹窗
            document.getElementById('feedbackModal').classList.add('active');
        }
        
        // 关闭弹窗
        function closeModal() {
            console.log('[用户反馈] 关闭弹窗');
            document.getElementById('feedbackModal').classList.remove('active');
            currentEditingItem = null;
        }
        
        // 保存反馈
        async function saveFeedback() {
            console.log('========== [用户反馈] 开始保存反馈 ==========');
            
            if (!currentEditingItem) {
                console.error('[用户反馈] 没有可保存的数据');
                alert('没有可保存的数据');
                return;
            }
            
            const originalIsReasonable = currentEditingItem.evaluation && currentEditingItem.evaluation.is_reasonable;
            const newLabelValue = document.getElementById('newLabel').value;
            const newIsReasonable = newLabelValue === 'reasonable';
            const userFeedback = document.getElementById('userFeedback').value.trim();
            
            // 🔥 新增：检查提示词是否有变化
            const currentPromptValue = document.getElementById('currentPrompt').value;
            const hasPromptChanged = currentPromptValue !== originalPrompt && currentPromptValue.length > 0;
            
            console.log('[用户反馈] 反馈信息:', {
                pair_id: currentEditingItem.pair_id,
                original_label: originalIsReasonable ? '合理' : '不合理',
                new_label: newIsReasonable ? '合理' : '不合理',
                label_changed: originalIsReasonable !== newIsReasonable,
                has_feedback: userFeedback.length > 0,
                has_prompt_changed: hasPromptChanged,
                prompt_length: currentPromptValue.length,
                original_prompt_length: originalPrompt.length
            });
            
            // 🔥 关键修复：如果没有修改标签、没有提供建议、也没有修改提示词，提示用户
            if (originalIsReasonable === newIsReasonable && !userFeedback && !hasPromptChanged) {
                console.warn('[用户反馈] 用户未做任何修改');
                console.warn('[用户反馈] - 标签未修改');
                console.warn('[用户反馈] - 未提供建议');
                console.warn('[用户反馈] - 提示词未修改');
                alert('请至少修改标签、提供建议或修改提示词');
                return;
            }
            
            // 🔥 增强调试日志：记录触发评估的原因
            const triggerReasons = [];
            if (originalIsReasonable !== newIsReasonable) {
                triggerReasons.push('标签已修改');
            }
            if (userFeedback) {
                triggerReasons.push('提供了建议');
            }
            if (hasPromptChanged) {
                triggerReasons.push('提示词已修改');
            }
            console.log(`[用户反馈] ✅ 满足保存条件，触发评估原因: ${triggerReasons.join(', ')}`);
            console.log(`[用户反馈] 详细信息:`);
            console.log(`[用户反馈] - 标签变化: ${originalIsReasonable ? '合理' : '不合理'} -> ${newIsReasonable ? '合理' : '不合理'}`);
            console.log(`[用户反馈] - 用户建议长度: ${userFeedback.length} 字符`);
            console.log(`[用户反馈] - 提示词变化: ${hasPromptChanged ? '是' : '否'} (${originalPrompt.length} -> ${currentPromptValue.length} 字符)`);
            
            // 在关闭弹窗之前，先保存必要的数据
            const savedPairId = currentEditingItem.pair_id;
            const savedUserMessage = currentEditingItem.user_message || '';
            const savedAiReply = currentEditingItem.ai_reply || '';
            const savedEvaluation = currentEditingItem.evaluation || {};
            
            // 在关闭弹窗之前，先找到要操作的卡片
            const currentIndex = currentMessageList.findIndex(msg => msg.pair_id === savedPairId);
            console.log('[用户反馈] 找到消息对索引:', currentIndex, 'pair_id:', savedPairId);
            
            // 立即关闭弹窗
            console.log('[用户反馈] 关闭弹窗');
            closeModal();
            
            // 添加加载状态在对应的消息卡片上
            let targetCard = null;
            if (currentIndex !== -1) {
                // 使用data-pair-id属性直接找到对应的卡片
                const messageElements = document.querySelectorAll('.message-item');
                console.log('[用户反馈] 当前页面有', messageElements.length, '个消息卡片');
                
                if (messageElements[currentIndex]) {
                    targetCard = messageElements[currentIndex];
                    const messageHeader = targetCard.querySelector('.message-header');
                    if (messageHeader) {
                        // 检查是否已经有加载指示器
                        let existingLoader = messageHeader.querySelector('.loading-badge');
                        if (existingLoader) {
                            existingLoader.remove();
                            console.log('[用户反馈] 移除了旧的加载指示器');
                        }
                        
                        // 添加加载状态
                        const loadingBadge = document.createElement('span');
                        loadingBadge.className = 'loading-badge';
                        loadingBadge.textContent = '🔄 正在重新评估...';
                        loadingBadge.style.cssText = 'background: #3b82f6; color: white; padding: 5px 10px; border-radius: 15px; font-size: 0.9em; margin-left: 10px; animation: pulse 1.5s infinite;';
                        
                        // 添加CSS动画
                        if (!document.getElementById('loading-animation-style')) {
                            const style = document.createElement('style');
                            style.id = 'loading-animation-style';
                            style.textContent = '@keyframes pulse { 0%, 100% { opacity: 1; } 50% { opacity: 0.5; } }';
                            document.head.appendChild(style);
                        }
                        
                        messageHeader.appendChild(loadingBadge);
                        console.log('[用户反馈] 已添加加载状态指示器到卡片头部');
                    } else {
                        console.error('[用户反馈] 找不到message-header元素');
                    }
                } else {
                    console.error('[用户反馈] 找不到索引为', currentIndex, '的消息卡片');
                }
            } else {
                console.error('[用户反馈] 未找到消息对索引');
            }
            
            try {
                // 获取当前使用的提示词（如果用户修改过）
                const currentPromptValue = document.getElementById('currentPrompt').value;
                const hasPromptChanged = currentPromptValue !== originalPrompt && currentPromptValue.length > 0;
                
                console.log('[用户反馈] 提示词是否有变化:', hasPromptChanged);
                console.log('[用户反馈] 当前提示词长度:', currentPromptValue.length);
                
                const requestData = {
                    pair_id: savedPairId,
                    original_label: originalIsReasonable ? '合理' : '不合理',
                    new_label: newIsReasonable ? '合理' : '不合理',
                    user_feedback: userFeedback,
                    user_message: savedUserMessage,
                    ai_reply: savedAiReply,
                    evaluation_reason: savedEvaluation.reason || '',
                    custom_prompt: hasPromptChanged ? currentPromptValue : null
                };
                
                console.log('[用户反馈] 发送请求数据:', requestData);
                
                const response = await fetch('/api/save-feedback', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(requestData)
                });
                
                const result = await response.json();
                console.log('[用户反馈] 服务器响应:', result);
                
                // 移除加载状态
                if (targetCard) {
                    const loadingBadge = targetCard.querySelector('.loading-badge');
                    if (loadingBadge) {
                        loadingBadge.remove();
                        console.log('[用户反馈] 已移除加载状态指示器');
                    }
                }
                
                if (result.success) {
                    // 更新本地数据和显示
                    const newEval = result.new_evaluation;
                    console.log('[用户反馈] 新评估结果:', newEval);
                    
                    // 更新本地数据（需要在evaluationData中找到对应的消息）
                    const messageInData = evaluationData.all_evaluations.find(e => e.pair_id === savedPairId);
                    if (messageInData && messageInData.evaluation) {
                        messageInData.evaluation.score = newEval.score;
                        messageInData.evaluation.is_reasonable = newEval.is_reasonable;
                        messageInData.evaluation.reason = newEval.reason;
                        messageInData.evaluation.strengths = newEval.strengths;
                        messageInData.evaluation.weaknesses = newEval.weaknesses;
                        console.log('[用户反馈] 已更新本地评估数据');
                    }
                    
                    // 更新消息卡片显示
                    if (targetCard && currentIndex !== -1) {
                        updateMessageCard(currentIndex, newEval, savedPairId);
                    }
                    
                    // 重新统计并更新卡片统计信息
                    console.log('[用户反馈] 开始重新统计并更新卡片统计信息');
                    updateStatisticsDisplay();
                    
                    // 🔥 关键修复：保存反馈后重新加载提示词，确保显示最新的提示词
                    console.log('[用户反馈] 保存反馈后重新加载提示词...');
                    await loadCurrentPrompt();
                    console.log('[用户反馈] 提示词已重新加载');
                    
                    console.log('[用户反馈] ========== 反馈保存成功 ==========');
                } else {
                    console.error('[用户反馈] 保存失败:', result.error);
                    alert('保存失败: ' + (result.error || '未知错误'));
                }
                
            } catch (error) {
                console.error('[用户反馈] 保存反馈时发生错误:', error);
                alert('保存失败: ' + error.message);
                
                // 移除加载状态
                if (targetCard) {
                    const loadingBadge = targetCard.querySelector('.loading-badge');
                    if (loadingBadge) {
                        loadingBadge.remove();
                        console.log('[用户反馈] 错误：已移除加载状态指示器');
                    }
                }
            }
        }
        
        // 更新消息卡片显示
        function updateMessageCard(index, newEval, pairId) {
            console.log('[用户反馈] ========== 开始更新消息卡片 ==========');
            console.log('[用户反馈] index:', index, 'pair_id:', pairId);
            console.log('[用户反馈] 新评估数据:', newEval);
            
            const messageElements = document.querySelectorAll('.message-item');
            if (index >= messageElements.length) {
                console.error('[用户反馈] 索引超出范围');
                return;
            }
            
            const messageElement = messageElements[index];
            
            // 更新评分徽章
            const scoreBadge = messageElement.querySelector('.score-badge');
            if (scoreBadge) {
                scoreBadge.className = `score-badge ${newEval.is_reasonable ? 'reasonable' : 'unreasonable'}`;
                scoreBadge.textContent = `${newEval.score}分 - ${newEval.is_reasonable ? '合理' : '不合理'}`;
                console.log('[用户反馈] ✅ 已更新评分徽章:', scoreBadge.textContent);
            } else {
                console.error('[用户反馈] ❌ 找不到评分徽章元素');
            }
            
            // 🔥 关键修复：更新评估理由，优先使用reason字段
            const reasonElement = messageElement.querySelector('.reason-text');
            if (reasonElement) {
                // 优先使用reason字段，如果没有则使用feedback_explanation
                const displayReason = newEval.reason || newEval.feedback_explanation || '未提供评估理由';
                reasonElement.textContent = displayReason;
                console.log('[用户反馈] ✅ 已更新评估理由 (前100字符):', displayReason.substring(0, 100));
                console.log('[用户反馈] 理由来源:', newEval.reason ? 'reason字段' : (newEval.feedback_explanation ? 'feedback_explanation字段' : '默认值'));
            } else {
                console.error('[用户反馈] ❌ 找不到评估理由元素 (.reason-text)');
            }
            
            // 🔥 新增：更新优点和缺点显示
            if (newEval.strengths && Array.isArray(newEval.strengths) && newEval.strengths.length > 0) {
                console.log('[用户反馈] 优点:', newEval.strengths);
            }
            if (newEval.weaknesses && Array.isArray(newEval.weaknesses) && newEval.weaknesses.length > 0) {
                console.log('[用户反馈] 缺点:', newEval.weaknesses);
            }
            
            // 移除旧的更新提示（如果存在）
            const oldIndicator = messageElement.querySelector('.update-indicator');
            if (oldIndicator) {
                oldIndicator.remove();
                console.log('[用户反馈] 已移除旧的更新提示');
            }
            
            // 添加更新提示
            const updateIndicator = document.createElement('div');
            updateIndicator.style.cssText = 'background: #10b981; color: white; padding: 5px 10px; border-radius: 5px; margin-top: 10px; font-size: 0.9em;';
            updateIndicator.textContent = '✅ 已根据您的反馈更新评估结果';
            updateIndicator.className = 'update-indicator';
            messageElement.appendChild(updateIndicator);
            console.log('[用户反馈] ✅ 已添加更新提示');
            
            // 3秒后自动移除更新提示
            setTimeout(() => {
                if (updateIndicator && updateIndicator.parentNode) {
                    updateIndicator.remove();
                    console.log('[用户反馈] 已自动移除更新提示');
                }
            }, 3000);
            
            // 加载评估记录
            console.log('[用户反馈] 开始加载评估记录, pair_id:', pairId);
            loadEvaluationHistory(pairId);
            
            console.log('[用户反馈] ========== 消息卡片更新完成 ==========');
        }
        
        // 重新统计并更新卡片统计信息
        function updateStatisticsDisplay() {
            console.log('[统计更新] 开始重新统计');
            
            if (!evaluationData || !evaluationData.all_evaluations) {
                console.error('[统计更新] 没有评估数据');
                return;
            }
            
            // 重新统计合理和不合理的数量
            let reasonableCount = 0;
            let unreasonableCount = 0;
            let failedCount = 0;
            
            evaluationData.all_evaluations.forEach(eval => {
                if (eval.status === 'evaluated' && eval.evaluation) {
                    // 🔥 关键修复：使用严格相等判断
                    if (normalizeReasonableValue(eval.evaluation.is_reasonable) === true) {
                        reasonableCount++;
                    } else if (normalizeReasonableValue(eval.evaluation.is_reasonable) === false) {
                        unreasonableCount++;
                    }
                } else if (eval.status === 'failed') {
                    failedCount++;
                }
            });
            
            console.log('[统计更新] 重新统计结果:', {
                total: evaluationData.all_evaluations.length,
                reasonable: reasonableCount,
                unreasonable: unreasonableCount,
                failed: failedCount
            });
            
            // 更新统计卡片显示
            const statsGrid = document.getElementById('statsGrid');
            if (statsGrid) {
                const totalPairs = evaluationData.all_evaluations.length;
                const reasonableRate = totalPairs > 0 ? ((reasonableCount / totalPairs) * 100).toFixed(2) : '0.00';
                
                statsGrid.innerHTML = `
                    <div class="stat-card">
                        <div class="label">📊 总消息对</div>
                        <div class="value">${totalPairs}</div>
                        <div class="subtext">已评估</div>
                    </div>
                    <div class="stat-card success">
                        <div class="label">✅ 合理回复</div>
                        <div class="value">${reasonableCount}</div>
                        <div class="subtext">占比 ${reasonableRate}%</div>
                    </div>
                    <div class="stat-card warning">
                        <div class="label">⚠️ 不合理回复</div>
                        <div class="value">${unreasonableCount}</div>
                        <div class="subtext">需要关注</div>
                    </div>
                    <div class="stat-card">
                        <div class="label">❌ 评估失败</div>
                        <div class="value">${failedCount}</div>
                        <div class="subtext">失败次数</div>
                    </div>
                `;
                
                console.log('[统计更新] 已更新统计卡片');
            } else {
                console.error('[统计更新] 找不到statsGrid元素');
            }
        }
        
        // 加载评估记录
        async function loadEvaluationHistory(pairId, options = {}) {
            const limit = options.limit || null;
            console.log('[评估记录] 开始加载评估历史, pair_id:', pairId, 'limit:', limit);
            const limitQuery = limit ? `&limit=${limit}` : '';

            try {
                const response = await fetch(`/api/get-feedback-history?pair_id=${pairId}${limitQuery}`);

                if (!response.ok) {
                    console.error('[评估记录] API调用失败:', response.status);
                    return;
                }

                const data = await response.json();
                console.log('[评估记录] API返回数据:', data);

                if (!data.success) {
                    console.warn('[评估记录] API返回失败:', data.error);
                    return;
                }

                updateLatestEvaluationCard(pairId, data.latest_record);
                displayEvaluationHistory(pairId, data.history, data.has_more_history);
                updateHistoryToggle(pairId, data.has_more_history, limit);

                console.log('[评估记录] 渲染完成, total=', data.total_records, 'historyLen=', data.history.length, 'hasMore=', data.has_more_history);
            } catch (error) {
                console.error('[评估记录] 加载评估历史时发生错误:', error);
            }
        }

        function displayEvaluationHistory(pairId, history, hasMore) {
            console.log('[评估记录] 显示评估记录, pair_id:', pairId, '记录数:', history ? history.length : 0, 'hasMore:', hasMore);

            const historyContainer = document.getElementById(`history-container-${pairId}`);
            if (!historyContainer) {
                console.error('[评估记录] 找不到history-container元素, pair_id:', pairId);
                return;
            }

            historyContainer.innerHTML = '<div class="history-header">📜 历史评估记录</div>';

            if (!history || history.length === 0) {
                historyContainer.innerHTML += '<div class="history-empty">暂无历史记录</div>';
                return;
            }

            const sortedHistory = [...history].sort((a, b) => new Date(b.feedback_timestamp) - new Date(a.feedback_timestamp));

            const itemsHtml = sortedHistory.map(record => {
                const isReasonable = record.new_is_reasonable === 1;
                const isAdopted = record.feedback_adopted === 1;
                const changed = record.changed === 1;

                let recordContent = '';
                if (changed) {
                    recordContent += `标签已从"${record.original_label}"修改为"${record.new_label}"<br>`;
                }
                if (record.user_feedback) {
                    recordContent += `💬 用户建议：${record.user_feedback}<br>`;
                }
                if (record.feedback_explanation) {
                    recordContent += `🤖 AI反馈：${record.feedback_explanation}`;
                }

                return `
                    <div class="history-item ${isReasonable ? 'reasonable' : 'unreasonable'}">
                        <div class="history-item-content">
                            <strong>${isReasonable ? '✅ 合理' : '⚠️ 不合理'} (${record.new_score}分)</strong>
                            ${isAdopted ? ' - ✅ AI已采纳反馈' : ''}
                        </div>
                        ${recordContent ? `<div class="history-item-content" style="margin-top: 6px;">${recordContent}</div>` : ''}
                        <div class="history-item-time">${new Date(record.feedback_timestamp).toLocaleString()}</div>
                    </div>
                `;
            }).join('');

            historyContainer.innerHTML += `<div class="history-list">${itemsHtml}</div>`;
        }

        function updateLatestEvaluationCard(pairId, latestRecord) {
            const latestContainer = document.getElementById(`latest-evaluation-${pairId}`);
            const messageCard = document.querySelector(`.message-item[data-pair-id="${pairId}"]`);
            console.log('[评估记录] 更新最新评估卡片, pair_id:', pairId, latestRecord);

            if (!latestContainer || !messageCard) {
                console.warn('[评估记录] 找不到最新评估容器或消息卡片, pair_id:', pairId);
                return;
            }

            const evaluationEntry = Array.isArray(evaluationData?.all_evaluations)
                ? evaluationData.all_evaluations.find(item => item.pair_id === pairId)
                : null;
            const evaluation = evaluationEntry && evaluationEntry.evaluation ? evaluationEntry.evaluation : null;

            const entryReasonable = evaluation ? normalizeReasonableValue(evaluation.is_reasonable) : undefined;
            const recordReasonable = latestRecord ? latestRecord.new_is_reasonable === 1 : undefined;

            const finalIsReasonable = entryReasonable !== undefined ? entryReasonable : (recordReasonable || false);
            const finalScore = evaluation && typeof evaluation.score === 'number'
                ? evaluation.score
                : (latestRecord ? latestRecord.new_score : 0);

            if (entryReasonable !== undefined && recordReasonable !== undefined && entryReasonable !== recordReasonable) {
                console.warn('[评估记录] 最新记录与evaluationData存在不一致，将以evaluationData为准', {
                    pair_id: pairId,
                    evaluation_is_reasonable: entryReasonable,
                    record_is_reasonable: recordReasonable
                });
            }

            const badge = messageCard.querySelector('.score-badge');
            if (badge) {
                badge.className = `score-badge ${finalIsReasonable ? 'reasonable' : 'unreasonable'}`;
                badge.textContent = `${finalScore}分 - ${finalIsReasonable ? '合理' : '不合理'}`;
            }

            const latestBody = latestContainer.querySelector('.latest-body');
            if (!latestBody) {
                return;
            }

            const strengths = evaluation && Array.isArray(evaluation.strengths)
                ? evaluation.strengths
                : (Array.isArray(latestRecord?.strengths) ? latestRecord.strengths : []);
            const weaknesses = evaluation && Array.isArray(evaluation.weaknesses)
                ? evaluation.weaknesses
                : (Array.isArray(latestRecord?.weaknesses) ? latestRecord.weaknesses : []);

            const reasonText = evaluation && evaluation.reason
                ? evaluation.reason
                : (latestRecord?.reason || latestRecord?.feedback_explanation || '未提供理由');

            const strengthsHtml = strengths.length > 0 ? `<div><strong>优点：</strong>${strengths.join(', ')}</div>` : '';
            const weaknessesHtml = weaknesses.length > 0 ? `<div><strong>缺点：</strong>${weaknesses.join(', ')}</div>` : '';

            latestBody.innerHTML = `
                <div class="reason-text">${reasonText}</div>
                ${strengthsHtml}
                ${weaknessesHtml}
            `;
        }

        function updateHistoryToggle(pairId, hasMore, currentLimit) {
            const historyContainer = document.getElementById(`history-container-${pairId}`);
            if (!historyContainer) {
                return;
            }

            let toggleButton = historyContainer.querySelector('.history-toggle');
            const shouldShow = hasMore || currentLimit === 'all';

            if (!shouldShow) {
                if (toggleButton) {
                    toggleButton.style.display = 'none';
                }
                return;
            }

            if (!toggleButton) {
                toggleButton = document.createElement('button');
                toggleButton.className = 'history-toggle';
                toggleButton.addEventListener('click', (event) => {
                    event.stopPropagation();
                    const currentState = toggleButton.dataset.state || 'collapsed';
                    const willExpand = currentState === 'collapsed';
                    loadEvaluationHistory(pairId, { limit: willExpand ? 'all' : null });
                });
                historyContainer.appendChild(toggleButton);
            }

            const isExpanded = currentLimit === 'all';
            toggleButton.dataset.state = isExpanded ? 'expanded' : 'collapsed';
            toggleButton.textContent = isExpanded ? '收起记录' : '展开更多记录';
            toggleButton.style.display = 'block';
        }
        
        // 编辑提示词
        function editPrompt() {
            console.log('[提示词编辑] 打开提示词编辑弹窗');
            document.getElementById('promptModal').classList.add('active');
            // 设置当前提示词到编辑框
            document.getElementById('newPrompt').value = currentPrompt;
        }
        
        // 对比提示词
        function comparePrompt() {
            console.log('[提示词对比] 点击查看原提示词');
            const originalSection = document.getElementById('originalPromptSection');
            if (originalSection.style.display === 'none') {
                // 显示原提示词
                originalSection.style.display = 'block';
                document.getElementById('originalPrompt').value = originalPrompt;
                console.log('[提示词对比] 显示原提示词');
            } else {
                // 隐藏原提示词
                originalSection.style.display = 'none';
                console.log('[提示词对比] 隐藏原提示词');
            }
        }
        
        // 关闭提示词编辑弹窗
        function closePromptModal() {
            console.log('[提示词编辑] 关闭提示词编辑弹窗');
            document.getElementById('promptModal').classList.remove('active');
        }
        
        // 保存提示词
        async function savePrompt() {
            console.log('[提示词编辑] 开始保存提示词');
            
            const newPrompt = document.getElementById('newPrompt').value.trim();
            if (!newPrompt) {
                alert('提示词不能为空');
                return;
            }
            
            try {
                const response = await fetch('/api/update-prompt', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        prompt: newPrompt,
                        category: 'reply_reasonable'
                    })
                });
                
                const result = await response.json();
                
                if (result.success) {
                    console.log('[提示词编辑] 提示词保存成功');
                    alert('✅ 提示词保存成功！');
                    currentPrompt = newPrompt;
                    document.getElementById('currentPrompt').value = newPrompt;
                    closePromptModal();
                } else {
                    console.error('[提示词编辑] 提示词保存失败:', result.error);
                    alert('保存失败: ' + (result.error || '未知错误'));
                }
                
            } catch (error) {
                console.error('[提示词编辑] 保存提示词时发生错误:', error);
                alert('保存失败: ' + error.message);
            }
        }
        
        // 获取当前使用的提示词
        async function loadCurrentPrompt() {
            console.log('[提示词] 加载当前使用的提示词');
            
            // 默认提示词（与后端ai_evaluator.py一致）- 参考客服话术标准优化版
            const defaultPrompt = `你是一个专业的AI智能客服对话质量评估专家，专门评估招聘直播主播岗位的客服回复质量。

## 背景信息
这是一个招聘直播主播岗位的客服系统。
- 工作性质：视频露脸直播主播（纯聊天类型，不需要才艺）
- 平台：B站（日结保底133元）或抖音（月结5000-8000元）
- 薪资模式：日结保底 + 礼物提成（30%-51%）

## 关键评估标准
1. 信息准确性（35%）- 薪资信息是否准确，是否提供了具体数字
2. 回复相关性（25%）- 是否直接回答了用户问题
3. 专业性（20%）- 是否避免过度口语化和欺骗性语言
4. 服务态度（15%）- 语气是否友好、耐心
5. 合法合规性（5%）- 是否避免欺诈性承诺

## 常见问题标准
- 薪资询问："4小时日结133元" vs "200-500元"（模糊）
- 保底询问：应明确说明"保底发放，没礼物也有保底"
- 工作时间：应说明"连播4小时，一周5-6天"

请给出详细的评估结果和理由。`;
            
            try {
                const response = await fetch('/api/get-prompt?category=reply_reasonable');
                
                if (!response.ok) {
                    console.error('[提示词] API调用失败:', response.status, '使用默认提示词');
                    // 使用默认提示词
                    currentPrompt = defaultPrompt;
                    document.getElementById('currentPrompt').value = currentPrompt;
                    return;
                }
                
                const data = await response.json();
                
                if (data.success && data.prompt) {
                    currentPrompt = data.prompt;
                    document.getElementById('currentPrompt').value = currentPrompt;
                    console.log('[提示词] 成功加载提示词，长度:', currentPrompt.length);
                } else {
                    console.log('[提示词] 暂无保存的提示词，使用默认提示词');
                    // 使用默认提示词
                    currentPrompt = defaultPrompt;
                    document.getElementById('currentPrompt').value = currentPrompt;
                }
                
            } catch (error) {
                console.error('[提示词] 加载提示词时发生错误:', error, '使用默认提示词');
                // 使用默认提示词
                currentPrompt = defaultPrompt;
                document.getElementById('currentPrompt').value = currentPrompt;
            }
        }
        
        // 导出数据
        async function exportData() {
            console.log('[回复合理评估] 开始导出数据');
            
            if (!evaluationData || !evaluationData.all_evaluations || evaluationData.all_evaluations.length === 0) {
                alert('没有可导出的评估数据');
                return;
            }
            
            try {
                const response = await fetch('/api/export-evaluations', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        evaluations: evaluationData.all_evaluations
                    })
                });
                
                if (!response.ok) {
                    throw new Error(`导出失败: ${response.status}`);
                }
                
                const result = await response.json();
                
                if (result.success) {
                    alert(`导出成功！\n导出数量: ${result.exported_count}\n文件路径: ${result.db_path}`);
                } else {
                    alert(`导出失败: ${result.error}`);
                }
                
            } catch (error) {
                console.error('[回复合理评估] 导出数据时发生错误:', error);
                alert(`导出失败: ${error.message}`);
            }
        }
        
        /**
         * 查看聊天历史记录
         */
        function viewChatHistory(candidateId, candidateName) {
            console.log('[查看聊天] ========== 准备查看聊天记录 ==========');
            console.log('[查看聊天] 候选人ID:', candidateId);
            console.log('[查看聊天] 候选人姓名:', candidateName);
            
            if (!candidateId) {
                console.error('[查看聊天] 候选人ID为空');
                alert('无法获取候选人信息');
                return;
            }
            
            // 构建目标URL，包含from参数以便返回
            const currentPage = 'reply_reasonable_detail.html';
            const targetUrl = `user_chat.html?candidate_id=${candidateId}&from=${encodeURIComponent(currentPage)}`;
            
            console.log('[查看聊天] 目标URL:', targetUrl);
            console.log('[查看聊天] 跳转到聊天记录页面...');
            
            // 跳转到聊天记录页面
            window.location.href = targetUrl;
        }
        
        /**
         * 🔥 新增：防抖处理的搜索函数
         */
        function debouncedFilterMessages() {
            // 清除之前的定时器
            if (searchDebounceTimer) {
                clearTimeout(searchDebounceTimer);
            }
            
            // 设置新的定时器，300ms后执行搜索
            searchDebounceTimer = setTimeout(() => {
                filterMessages();
            }, 300);
        }
        
        /**
         * 🔥 新增：搜索过滤功能
         * 实时过滤消息列表
         */
        function filterMessages() {
            console.log('========== [搜索过滤] 开始过滤消息 ==========');
            
            // 安全性检查
            const searchInput = document.getElementById('messageSearchInput');
            if (!searchInput) {
                console.error('[搜索过滤] ❌ 搜索框元素不存在');
                return;
            }
            
            if (!allDisplayedMessages || allDisplayedMessages.length === 0) {
                console.warn('[搜索过滤] ⚠️ 没有可搜索的消息');
                return;
            }
            
            const searchTerm = searchInput.value.trim().toLowerCase();
            
            console.log(`[搜索过滤] 搜索关键词: "${searchTerm}"`);
            console.log(`[搜索过滤] 总消息数: ${totalMessageCount}`);
            
            // 如果搜索词为空，显示所有消息
            if (!searchTerm) {
                console.log('[搜索过滤] 搜索词为空，显示所有消息');
                allDisplayedMessages.forEach(item => {
                    if (item && item.classList) {
                        item.classList.remove('hidden');
                    }
                });
                updateSearchStats(totalMessageCount, totalMessageCount);
                const clearBtn = document.getElementById('clearSearchBtn');
                if (clearBtn) clearBtn.disabled = true;
                console.log(`[搜索过滤] ✅ 已显示全部 ${totalMessageCount} 条消息`);
                return;
            }
            
            // 启用清除按钮
            const clearBtn = document.getElementById('clearSearchBtn');
            if (clearBtn) clearBtn.disabled = false;
            
            let visibleCount = 0;
            let hiddenCount = 0;
            
            // 使用requestAnimationFrame优化性能
            requestAnimationFrame(() => {
                // 遍历所有消息元素进行过滤
                allDisplayedMessages.forEach((item, index) => {
                    if (!item || !item.classList) {
                        console.warn(`[搜索过滤] ⚠️ 消息元素 #${index} 无效`);
                        return;
                    }
                    
                    try {
                        // 获取消息卡片中的关键文本内容
                        // 只搜索：候选人姓名、用户消息、AI回复
                        const candidateName = item.querySelector('.candidate-name')?.textContent.toLowerCase() || '';
                        const userMessage = item.querySelector('.message-box.user .message-text')?.textContent.toLowerCase() || '';
                        const aiReply = item.querySelector('.message-box.ai .message-text')?.textContent.toLowerCase() || '';
                        
                        // 组合可搜索的文本（不包括评估理由和pair_id）
                        const searchableText = `${candidateName} ${userMessage} ${aiReply}`;
                        
                        // 判断是否匹配搜索词
                        const isMatch = searchableText.includes(searchTerm);
                        
                        if (isMatch) {
                            item.classList.remove('hidden');
                            visibleCount++;
                            
                            // 记录匹配详情（仅前3条）
                            if (visibleCount <= 3) {
                                const displayName = candidateName.substring(0, 20) || '未知';
                                console.log(`[搜索过滤] ✅ 匹配 #${visibleCount}: 候选人="${displayName}"`);
                            }
                        } else {
                            item.classList.add('hidden');
                            hiddenCount++;
                        }
                    } catch (error) {
                        console.error(`[搜索过滤] ❌ 处理消息 #${index} 时出错:`, error);
                    }
                });
                
                // 更新统计信息
                updateSearchStats(visibleCount, totalMessageCount);
                
                console.log('[搜索过滤] ========== 过滤完成 ==========');
                console.log(`[搜索过滤] 📊 统计结果:`);
                console.log(`  - 显示消息: ${visibleCount} 条`);
                console.log(`  - 隐藏消息: ${hiddenCount} 条`);
                console.log(`  - 总消息数: ${totalMessageCount} 条`);
                console.log(`  - 匹配率: ${((visibleCount / totalMessageCount) * 100).toFixed(2)}%`);
                
                // 如果没有匹配结果，给出提示
                if (visibleCount === 0) {
                    console.warn('[搜索过滤] ⚠️ 未找到匹配的消息');
                }
            });
        }
        
        /**
         * 更新搜索统计信息
         */
        function updateSearchStats(visibleCount, totalCount) {
            const searchStats = document.getElementById('searchStats');
            
            if (!searchStats) {
                console.error('[搜索统计] ❌ 统计元素不存在');
                return;
            }
            
            if (visibleCount === totalCount) {
                searchStats.textContent = `显示全部消息 (${totalCount})`;
                searchStats.style.borderColor = '#667eea';
                searchStats.style.color = '#667eea';
                console.log(`[搜索统计] 显示全部消息: ${totalCount} 条`);
            } else {
                searchStats.textContent = `找到 ${visibleCount} / ${totalCount} 条消息`;
                searchStats.style.borderColor = visibleCount > 0 ? '#10b981' : '#f59e0b';
                searchStats.style.color = visibleCount > 0 ? '#10b981' : '#f59e0b';
                console.log(`[搜索统计] 过滤结果: ${visibleCount} / ${totalCount} 条`);
            }
        }
        
        /**
         * 清除搜索
         */
        function clearSearch() {
            console.log('[搜索过滤] 清除搜索条件');
            
            const searchInput = document.getElementById('messageSearchInput');
            if (!searchInput) {
                console.error('[搜索过滤] ❌ 搜索框元素不存在');
                return;
            }
            
            searchInput.value = '';
            
            // 直接触发过滤函数（不使用防抖）
            filterMessages();
            
            // 让搜索框失去焦点
            searchInput.blur();
            
            console.log('[搜索过滤] ✅ 搜索已清除，已显示所有消息');
        }
        
        /**
         * 🔥 新增：按时间排序消息
         */
        function sortMessagesByTime(messages, order) {
            console.log(`[时间排序] 开始排序，顺序: ${order}, 消息数: ${messages.length}`);
            
            if (!messages || messages.length === 0) {
                console.warn('[时间排序] ⚠️ 消息列表为空');
                return [];
            }
            
            // 复制数组避免修改原数组
            const sortedMessages = [...messages];
            
            sortedMessages.sort((a, b) => {
                const timeA = new Date(a.created_at || 0).getTime();
                const timeB = new Date(b.created_at || 0).getTime();
                
                if (order === 'asc') {
                    // 升序：早到晚
                    return timeA - timeB;
                } else {
                    // 降序：晚到早
                    return timeB - timeA;
                }
            });
            
            // 打印前3条消息的时间用于验证
            if (sortedMessages.length > 0) {
                console.log('[时间排序] 前3条消息时间:');
                sortedMessages.slice(0, 3).forEach((msg, idx) => {
                    const time = formatTimestamp(msg.created_at);
                    console.log(`  ${idx + 1}. ${time}`);
                });
            }
            
            console.log('[时间排序] ✅ 排序完成');
            return sortedMessages;
        }
        
        /**
         * 🔥 新增：切换排序顺序
         */
        function toggleSortOrder() {
            console.log('========== [时间排序] 切换排序顺序 ==========');
            console.log(`[时间排序] 当前顺序: ${currentSortOrder}`);
            
            // 切换排序顺序
            currentSortOrder = currentSortOrder === 'asc' ? 'desc' : 'asc';
            
            console.log(`[时间排序] 新顺序: ${currentSortOrder}`);
            
            // 更新按钮显示
            const sortBtn = document.getElementById('sortTimeBtn');
            const sortText = document.getElementById('sortTimeText');
            
            if (sortBtn && sortText) {
                sortBtn.setAttribute('data-order', currentSortOrder);
                
                if (currentSortOrder === 'asc') {
                    sortText.textContent = '时间升序';
                    sortBtn.title = '当前：早→晚，点击切换';
                    console.log('[时间排序] 按钮更新为：时间升序 ⬆');
                } else {
                    sortText.textContent = '时间降序';
                    sortBtn.title = '当前：晚→早，点击切换';
                    console.log('[时间排序] 按钮更新为：时间降序 ⬇');
                }
            }
            
            // 重新渲染消息列表
            if (currentMessageType && originalMessageData.length > 0) {
                console.log('[时间排序] 重新渲染消息列表...');
                
                // 按新顺序排序
                const sortedMessages = sortMessagesByTime(originalMessageData, currentSortOrder);
                
                // 重新渲染HTML
                const messageList = document.getElementById('messageList');
                const type = currentMessageType;
                
                messageList.innerHTML = sortedMessages.map((msg, index) => {
                    const evaluation = msg.evaluation || {};
                    const score = evaluation.score || 0;
                    const isReasonable = normalizeReasonableValue(evaluation.is_reasonable);
                    const reason = evaluation.reason || '未提供理由';
                    const strengths = evaluation.strengths || [];
                    const weaknesses = evaluation.weaknesses || [];
                    const pairId = msg.pair_id;
                    const timestamp = msg.created_at || '';
                    
                    return `
                        <div class="message-item ${isReasonable ? 'reasonable' : 'unreasonable'}" data-pair-id="${pairId}" onclick="openModal(${index}, '${type}')">
                            <div class="message-header">
                                <div class="candidate-name">${msg.candidate_name || `候选人 #${msg.candidate_id || '未知'}`}</div>
                                <div style="display: flex; gap: 10px; align-items: center;">
                                    <button class="view-chat-btn" 
                                            data-candidate-id="${msg.candidate_id}" 
                                            data-candidate-name="${(msg.candidate_name || '未知').replace(/"/g, '&quot;')}"
                                            data-pair-id="${pairId}"
                                            style="padding: 5px 12px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); 
                                                   color: white; border: none; border-radius: 15px; cursor: pointer; font-size: 0.85em; 
                                                   transition: all 0.3s; box-shadow: 0 2px 5px rgba(0,0,0,0.2);"
                                            onmouseover="this.style.transform='translateY(-2px)'; this.style.boxShadow='0 4px 10px rgba(0,0,0,0.3)';"
                                            onmouseout="this.style.transform='translateY(0)'; this.style.boxShadow='0 2px 5px rgba(0,0,0,0.2)';">
                                        💬 查看聊天
                                    </button>
                                    <span class="score-badge ${msg.evaluation && normalizeReasonableValue(msg.evaluation.is_reasonable) ? 'reasonable' : 'unreasonable'}">
                                        ${msg.evaluation && normalizeReasonableValue(msg.evaluation.is_reasonable) ? '✅ 合理' : '⚠️ 不合理'}
                                        (评分: ${msg.evaluation?.score || 0}分)
                                    </span>
                                </div>
                            </div>
                            <div class="message-content">
                                <div class="message-box user">
                                    <div class="message-label">👤 用户消息：</div>
                                    <div class="message-text">${formatUserMessage(msg.user_message)}</div>
                                </div>
                                <div class="message-box ai">
                                    <div class="message-label">🤖 AI回复：</div>
                                    <div class="message-text">${msg.ai_reply || ''}</div>
                                </div>
                                <div class="message-timestamp">${formatTimestamp(timestamp)}</div>
                            </div>
                            <div class="evaluation-latest" id="latest-evaluation-${pairId}">
                                <div class="latest-header">🆕 最新评估结果</div>
                                <div class="latest-body">
                                    <div class="reason-text">${reason}</div>
                                    ${strengths.length > 0 ? `<div><strong>优点：</strong>${strengths.join(', ')}</div>` : ''}
                                    ${weaknesses.length > 0 ? `<div><strong>缺点：</strong>${weaknesses.join(', ')}</div>` : ''}
                                </div>
                            </div>
                            <div class="evaluation-history-inline" data-pair-id="${pairId}" id="history-container-${pairId}">
                                <!-- 历史记录加载区域 -->
                            </div>
                        </div>
                    `;
                }).join('');
                
                // 更新消息元素引用
                allDisplayedMessages = document.querySelectorAll('.message-item');
                
                // 重新加载评估记录
                setTimeout(() => {
                    sortedMessages.forEach(msg => {
                        if (msg.pair_id !== undefined && msg.pair_id !== null) {
                            loadEvaluationHistory(msg.pair_id);
                        }
                    });
                    
                    // 重新添加查看聊天按钮事件
                    document.querySelectorAll('.view-chat-btn').forEach(btn => {
                        btn.addEventListener('click', function(e) {
                            e.stopPropagation();
                            e.preventDefault();
                            const candidateId = this.getAttribute('data-candidate-id');
                            const candidateName = this.getAttribute('data-candidate-name');
                            viewChatHistory(candidateId, candidateName);
                        });
                    });
                }, 100);
                
                // 如果有搜索条件，重新应用过滤
                const searchInput = document.getElementById('messageSearchInput');
                if (searchInput && searchInput.value.trim()) {
                    console.log('[时间排序] 重新应用搜索过滤...');
                    filterMessages();
                }
                
                console.log('[时间排序] ✅ 消息列表重新渲染完成');
            } else {
                console.warn('[时间排序] ⚠️ 没有消息数据可排序');
            }
            
            console.log('[时间排序] ========== 排序切换完成 ==========');
        }
    </script>
</body>
</html>
